//
//  DTLogInViewController.m
//  DatangLife
//
//  Created by 陈建 on 2018/5/20.
//  Copyright © 2018年 DatangLife. All rights reserved.
//

#import "DTLogInViewController.h"

#define codeAppkey @"5c4b80ebc844d7695c425a93ee4565ab"

@interface DTLogInViewController ()
{
    NSString *_iphoneNum;
    NSString *_codeNum;
    NSString *_yaoNum;
    NSString *_fasongCodeNum;
    NSString *_fasongMobie;
    BOOL _isGetCode;
}

@property (weak, nonatomic) IBOutlet UIView *lineView1;
@property (weak, nonatomic) IBOutlet UIView *lineView2;
@property (weak, nonatomic) IBOutlet UILabel *iphoneNumHeaderLable;
@property (weak, nonatomic) IBOutlet UITextField *iphoneNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
//@property (weak, nonatomic) IBOutlet UIButton *noGetCodeBtn;
//@property (weak, nonatomic) IBOutlet UIButton *selectBtn;
//@property (weak, nonatomic) IBOutlet UIButton *userBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *inviteNumTextField;
@property (weak, nonatomic) IBOutlet UIView *lineView3;

@end

@implementation DTLogInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    [self configerUI];
    
    _isGetCode = NO;
   _fasongCodeNum = [NSString stringWithFormat:@"%f",MAXFLOAT];
    // Do any additional setup after loading the view from its nib.
}

- (void)configerUI{
    self.getCodeBtn.backgroundColor = kWhiteColor;
    [self.getCodeBtn setTitleColor:[UIColor colorWithHexString:kDetailTextGrayBlackColor] forState:UIControlStateNormal];
    self.getCodeBtn.layer.borderColor = [UIColor colorWithHexString:kDetailTextGrayBlackColor].CGColor;
    
    self.getCodeBtn.layer.borderWidth = 0.5;
    self.iphoneNumHeaderLable.textColor = [UIColor colorWithHexString:kNomalTextBlackColor];
    self.lineView1.backgroundColor = self.lineView2.backgroundColor  = self.lineView3.backgroundColor = [UIColor colorWithHexString:kLineViewBgColor];
    self.loginBtn.enabled = NO;
    self.loginBtn.layerCornerRadius = 20;
    [self.loginBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
//    [self.noGetCodeBtn setTitleColor:[UIColor colorWithHexString:kDetailTextGrayBlackColor] forState:UIControlStateNormal];
//    [self.userBtn setTitleColor:[UIColor colorWithHexString:kDetailTextGrayBlackColor] forState:UIControlStateNormal];
    [self.iphoneNumTextField addTarget:self action:@selector(iphoneNumTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.codeTextField addTarget:self action:@selector(codeTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.inviteNumTextField addTarget:self action:@selector(inviteNumTextField:) forControlEvents:UIControlEventEditingChanged];
    self.loginBtn.backgroundColor = [UIColor colorWithHexString:kDetailTextGrayBlackColor];
    
    
//    [self.selectBtn setImage:[UIImage imageNamed:@"DT_Login_noSelect"] forState:UIControlStateNormal];
//    [self.selectBtn setImage:[UIImage imageNamed:@"DT_Login_select"] forState:UIControlStateSelected];
//    self.selectBtn.selected = YES;
    
}

- (void)iphoneNumTextField:(UITextField *)textField{
    _iphoneNum = textField.text;
    [self setupLogBtnBackGroundColor];
    
}
- (void)codeTextField:(UITextField *)textField{
    _codeNum = textField.text;
    [self setupLogBtnBackGroundColor];
}



- (void)setupLogBtnBackGroundColor{
    if (_iphoneNum.length > 0 && _codeNum.length > 0) {
        self.loginBtn.backgroundColor =kCommonRedColor;
        self.loginBtn.enabled = YES;
    }else{
        self.loginBtn.backgroundColor = [UIColor colorWithHexString:kDetailTextGrayBlackColor];
        self.loginBtn.enabled = NO;
    }
}
- (IBAction)getCodeClick:(id)sender {
    
    if (![_iphoneNum validateMobile]) {
        [CJUIKit showErrorWithStatus:@"手机号码不正确"];
    }else {
        
        NSString *resString = [NSString string];
        for (NSInteger i = 0 ; i< 4; i++) {
            int suiji = arc4random() % 10 ;
            NSString *str = [NSString stringWithFormat:@"%d",suiji];
            
            resString = [NSString stringWithFormat:@"%@%@",resString,str];
        }
        

        NSString *codeString = [NSString stringWithFormat:@"【VE财经】验证码：%@,VE财经账号登录验证，5分钟内有效（请勿泄露）",resString];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 6.f;
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
        
        [manager POST:@"https://v.apistore.cn/api/v14/send" parameters:@{@"key":codeAppkey,@"mobile":_iphoneNum,@"content":codeString} progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * responseObj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
             NSLog(@"%@",responseObj);
            if ([responseObj[@"error_code"] integerValue] == 0) {
                self->_fasongMobie = self->_iphoneNum;
                [self.iphoneNumTextField resignFirstResponder];
                [self.codeTextField becomeFirstResponder];
                [sender startWithTime:300 title:@"获取验证码" countDownTitle:@"s" mainColor:kWhiteColor countColor:kWhiteColor];
                self->_fasongCodeNum = resString;
                self->_isGetCode = YES;
            }else{
                [CJUIKit showErrorWithStatus:@"获取验证码失败"];
                self->_isGetCode = NO;
                self->_fasongCodeNum = [NSString stringWithFormat:@"%f",MAXFLOAT];
            }
           
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [CJUIKit showErrorWithStatus:@"获取验证码失败"];
            self->_isGetCode = NO;
            self->_fasongCodeNum = [NSString stringWithFormat:@"%f",MAXFLOAT];
        }];
    }
}

//- (IBAction)userXiyiClick:(id)sender {
//    DTHtmlWebViewController *vc = [[DTHtmlWebViewController alloc] init];
//    vc.title = @"用户协议";
//    vc.type = 1;
//    [self pushVc:vc];
//}

- (void)inviteNumTextField:(UITextField *)textField{
    _yaoNum = textField.text;
}

- (IBAction)logInBtnClick:(id)sender {
    [self.view endEditing:YES];
    
    if ([_iphoneNum isEqualToString:@"13484459231"]) {
        NSDictionary *dic =@{@"Telephone":_iphoneNum,@"vecode":@""};
        CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:[NSString stringWithFormat:@"%@/VEService/Login.do",kPublicInterfaceAPI] isPost:YES withParameters:dic];
        [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
            
            NSLog(@"%@",response);
            NSDictionary *userInfo = response[0];
            [[CJUserInfoManager sharedManager] didLoginInWithUserInfo:userInfo];
            self.loginSuccessBlock();
            [self pop];
            
        }];
    } else {
        if (![_codeNum isEqualToString:_fasongCodeNum] || _fasongMobie != _iphoneNum) {
            [CJUIKit showErrorWithStatus:@"验证码错误"];
        }else{
            NSDictionary *dic = [NSDictionary dictionary];
            if (_yaoNum.length == 0) {
                dic =@{@"Telephone":_iphoneNum,@"vecode":@""};
            }else{
                dic =@{@"Telephone":_iphoneNum,@"vecode":_yaoNum};
            }
            CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:[NSString stringWithFormat:@"%@/VEService/Login.do",kPublicInterfaceAPI] isPost:YES withParameters:dic];
            [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                
                NSLog(@"%@",response);
                NSDictionary *userInfo = response[0];
                [[CJUserInfoManager sharedManager] didLoginInWithUserInfo:userInfo];
                self.loginSuccessBlock();
                [self pop];
                
            }];
        }
    }
    
    
    
}
- (IBAction)selectBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
//    sender.selected = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
